import { createRouter, createWebHistory } from 'vue-router'
import { useAuthStore } from '@/store/auth'

const routes = [
    {
        path: '/login',
        name: 'Login',
        component: () => import('@/views/auth/Login.vue'),
        meta: { title: '登录', guestOnly: true, requiresAuth: false }
    },
    {
        path: '/',
        name: 'Dashboard',
        component: () => import('@/views/dashboard/Dashboard.vue'),
        meta: { title: '仪表盘', requiresAuth: true }
    },
    {
        path: '/personal',
        name: 'Personal', // 添加路由名称
        component: () => import('@/views/Personal.vue'),
        meta: { title: '个人中心', requiresAuth: true }
    },
    {
        path: '/users',
        name: 'UserList', // 添加路由名称
        component: () => import('@/views/User/List.vue'),
        meta: { title: '用户管理', requiresAuth: true }
    },
    {
        path: '/menus',
        name: 'MenuList', // 添加路由名称
        component: () => import('@/views/MenuList.vue'),
        meta: { title: '菜单管理', requiresAuth: true }
    },
    {
        path: '/chicken',
        name: 'Chicken', // 添加路由名称
        component: () => import('@/views/chicken/Chicken.vue'),
        meta: { title: '吃饭管理' }
    },
    {
        path: '/chicken/order',
        component: () => import('@/views/chicken/OrderMeal.vue'),
    },
    {
        path: '/chicken/manage/meal',
        component: () => import('@/views/chicken/MealManage.vue'),
    },
    // 添加404兜底路由
    {
        path: '/:pathMatch(.*)*',
        redirect: '/'
    }
]

const router = createRouter({
    history: createWebHistory(),
    routes,
    scrollBehavior(to, from, savedPosition) {
        return savedPosition || { top: 0 }
    }
})

// 增强路由守卫
router.beforeEach((to, from, next) => {
    const authStore = useAuthStore()
    console.log('路由跳转至:', to.path)

    if (to.matched.some(record => record.meta.requiresAuth)) {
        if (!authStore.isAuthenticated()) {
            next({
                path: '/login',
                query: { redirect: to.fullPath }
            })
        } else {
            next()
        }
    } else if (to.matched.some(record => record.meta.guestOnly)) {
        if (authStore.isAuthenticated()) {
            next('/')
        } else {
            next()
        }
    } else {
        next()
    }
})

export default router